/**
 * Copyright (c) CSIRO Australia, 2009
 *
 * @author $Author: jia020 $
 * @version $Id: ParamsParser.java 643 2009-05-20 00:20:55Z jia020 $
 */
package au.csiro.nt.pdsp.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * Parser for XML Document Type Params.
 * 
 * An example of this is: <span> <code>
 * <params><param id="1" key="DBNAME" value="pdsp"><param id="2" key="DBPIN" value="xxx"></param></params>
 * </code> </span>
 * 
 */
public class ParamsParser {

	/**
	 * Map to hold all the key-value pairs of each parameter.
	 */
	Map<String, String> mapParams = null;

	/**
	 * XML element name that represents a single parameter.
	 */
	private final String XML_TAG = "param";

	/**
	 * The XML attribute of a parmeter that contains the key.
	 */
	private final String KEY_XML_ATTR = "key";

	/**
	 * The XML attribute of a parmeter that contains the value.
	 */
	private final String VALUE_XML_ATTR = "value";

	/**
	 * Default constructor.
	 */
	public ParamsParser() {
		this.mapParams = new HashMap<String, String>();

	} // End of default constructor.

	/**
	 * Returns the <b>reference</b> to a {@link java.util.Map} that contains the
	 * parameters.
	 * 
	 * @return {@link java.util.Map} <b>Reference</b> to parameters represented as
	 *         key-value pairs.
	 */
	public Map<String, String> getMap() {
		return this.mapParams;

	} // End of `ProtocolParams.getMap` method.

	/**
	 * Get value of parameter by a key
	 * 
	 * @param key
	 *          Name of parameter to look for.
	 * 
	 * @return value Value of parameter corresponding to the supplied
	 *         <code>key</code> as a {@link java.lang.String}. <code>null</code>
	 *         if value is not found.
	 */
	public String getParam(String key) {
		if (mapParams != null) {
			return mapParams.get(key);
		} else {
			return null;
		}

	} // End of `ProtocolParams.getParam` method.

	public int loadParams(String xml) {
		int size = 0;
		com.google.gwt.xml.client.Document doc = XMLParser.parse(xml);
		NodeList nodes = doc.getElementsByTagName(XML_TAG);

		if (nodes != null && nodes.getLength() > 0) {
			String key = null;
			String value = null;
			for (int i = 0; i < nodes.getLength(); i++) {
				Element node = (Element) nodes.item(i);
				key = node.getAttributes().getNamedItem(this.KEY_XML_ATTR)
						.getNodeValue();
				value = node.getAttributes().getNamedItem(this.VALUE_XML_ATTR)
						.getNodeValue();
				mapParams.put(key, value);
				size++;
			}
		}
		return size;

	} // End of `XMLParamsParser.loadParams` method.
} // End of `XMLParamsParser` class
